import axios from 'axios'
import store from '@/store'
import router from '@/router'

const instance = axios.create({
  baseURL: 'http://127.0.0.1',
  timeout: 3000
})

// 设置拦截器
// 请求拦截器
instance.interceptors.request.use((config) => {
  if (config.url.startsWith('/my')) {
    config.headers.Authorization = 'Bearer ' + store.state.token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use((response) => {
  // console.log(1)
  return response
}, (error) => {
  console.log(2)
  // 处理响应失败的情况 4xx 5xx
  // console.dir(error)
  if (error.response.status === 401) {
    // 清空token并跳转到登录页
    store.commit('setToken', '')
    store.commit('setUserInfo', {})
    router.push('/login')
  }
  return Promise.reject(error)
})

export default instance
